// 长按指令

import { DirectiveBinding } from "vue/types/options"
interface ElType extends HTMLElement {
  $value: string
  handler: () => void
}

const longpress = {
  bind: function (el: ElType, binding: DirectiveBinding) {
    if (typeof binding.value !== 'function') {
      throw 'callback must be a function'
    }
    // 定义变量
    let pressTimer: number
    // 运行函数
    el.handler = () => {
      binding.value()
    }
    // 创建计时器（ 2秒后执行函数 ）
    const start = (e: any) => {
      if (e.type === 'click' && e.button !== 0) {
        return
      }
      if (pressTimer === null) {
        pressTimer = setTimeout(() => {
          el.handler()
        }, 2000)
      }
    }
    // 取消计时器
    const cancel = () => {
      if (pressTimer !== null) {
        clearTimeout(pressTimer)
        pressTimer = null as unknown as number
      }
    }
    // 添加事件监听器
    el.addEventListener('mousedown', start)
    el.addEventListener('touchstart', start)
    // 取消计时器
    el.addEventListener('click', cancel)
    el.addEventListener('mouseout', cancel)
    el.addEventListener('touchend', cancel)
    el.addEventListener('touchcancel', cancel)
  },
  // 当传进来的值更新的时候触发
  componentUpdated(el: ElType, { value }: DirectiveBinding) {
    el.$value = value
  },
  // 指令与元素解绑的时候，移除事件绑定
  unbind(el: ElType) {
    el.removeEventListener('click', el.handler)
  },
}

export default longpress